package com.itheima.util;


import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
import java.util.ResourceBundle;

public class JdbcUtil {
    private JdbcUtil() {
    }

    private static String url;
    private static String username;
    private static String password;

    static {
        //InputStream is = JdbcUtils.class.getResourceAsStream("/db.properties");
        InputStream is = JdbcUtil.class.getClassLoader().getResourceAsStream("db.properties");
        Properties prop = new Properties();
        String classDriver = null;
        try {
            prop.load(is);
            classDriver = prop.getProperty("ClassDriver");
            url = prop.getProperty("url");
            username = prop.getProperty("username");
            password = prop.getProperty("password");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        try {
            Class.forName(classDriver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConn() throws SQLException {
        Connection connection = DriverManager.getConnection(url, username, password);
        return connection;
    }

    public static void close(Connection conn, PreparedStatement pst, ResultSet res) {
        try {
            if (conn != null)
                conn.close();
            if (pst != null)
                pst.close();
            if (res != null)
                res.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(Connection conn, PreparedStatement pst) throws Exception {
        close(conn, pst, null);
    }
}

